﻿'copyright 2011 Jason Bean

Imports System.IO
Imports Microsoft.WindowsAPICodePack
Imports Microsoft.WindowsAPICodePack.Taskbar
'Imports System.Text.RegularExpressions

Public Class frmBatchVideo
    Dim KillHB As Boolean

    Private Sub btnEncode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncode.Click
        Dim VideoCount As Integer
        Dim handbrake As New Process
        Dim EncodeTo As String = ""
        Dim CropVideo As String = ""
        Dim Outfile As String
        Dim InPath As String
        Dim edlFile As String
        Dim Args As String = ""
        Dim output As String()
        Dim percentage As Single = 0
        Dim AllProgress As Single = 0
        Dim DeletePoster As Boolean

        'If on Windows 7 ore greater set the taskbar progress state to normal
        If OsMajor >= 6 And OsMinor >= 1 Then
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal)
        End If

        'disable buttons and radio controls during encoding
        btnAdd.Enabled = False
        btnRemove.Enabled = False
        btnClear.Enabled = False
        btnSettings.Enabled = False
        btnEncode.Enabled = False
        grpEncDest.Enabled = False

        'get the number of videos to encode
        VideoCount = lstVideos.Items.Count

        'check which profile to use and set EncodeTo string appropriately
        If iphone.Checked Then
            EncodeTo = "iPhone & iPod Touch"
        ElseIf ipod.Checked Then
            EncodeTo = "iPod"
        End If

        'check if autocrop is turned on and set string
        If Not AutoCrop Then
            CropVideo = "--crop 0:0:0:0 "
        End If




        If AutoTVMeta Or AutoMoviePoster Then
            Dim FileNameSplit() As String
            Dim MetaData(5) As String
            Dim SeriesID As Long
            Dim EpisodeData(1) As Integer
            Dim Poster As String = ""
            Dim TVFound As Boolean = False
            Dim MovieFound As Boolean = False
            Dim Title As String = ""
            Dim TMDbID() As String = {"", String.Empty}

            'Set Array Length for Args & Posters variables
            ReDim AtomicArgs(VideoCount - 1)
            ReDim Posters(VideoCount - 1)

            For Video As Integer = 0 To (VideoCount - 1)
                Outfile = Path.GetFileNameWithoutExtension(lstVideos.Items(Video).ToString)

                'Get metadata from SageTV recording
                MetaData = GetMetaData(lstVideos.Items(Video))

                'Split Filename
                FileNameSplit = Split(Outfile, " - ")

                If FileNameSplit.Length >= 3 And AutoTVMeta Then ' If the filename has three or more segments it means it could be a TV show

                    'Get Show title and episode name from filename
                    MetaData(0) = FileNameSplit(0)
                    MetaData(1) = FileNameSplit(2)

                    'Get season number and episode number from filename assuming format SxxExx or similar
                    EpisodeData(0) = CInt(FileNameSplit(1).Substring(1, 2))
                    EpisodeData(1) = CInt(FileNameSplit(1).Substring(4, 2))

                    'Get TVDB series ID using series title
                    SeriesID = GetSeriesID(MetaData(0))
                    If SeriesID > 0 Then 'Make sure a series ID has been found before getting poster
                        'Get poster using TVDB series ID
                        Poster = GetTVPoster(SeriesID)
                        'Indicate it has been found
                        TVFound = True
                    End If
                ElseIf MetaData(0) <> String.Empty And MetaData(1) <> String.Empty And AutoTVMeta Then 'Otherwise if check to make sure the metadata exists
                    'Get series ID using the series title and ID
                    SeriesID = GetSeriesID(MetaData(0), MetaData(2))
                    'Get the season number and episode number
                    If SeriesID > 0 Then 'If a series ID was found continue
                        EpisodeData = GetEpisodeData(MetaData(1), SeriesID)
                        'Use the file metadata if TVDB search failed
                        If EpisodeData(0) = 0 And EpisodeData(1) = 0 And CInt(MetaData(3)) > 0 And CInt(MetaData(4)) > 0 Then
                            EpisodeData(0) = CInt(MetaData(3))
                            EpisodeData(1) = CInt(MetaData(4))
                        End If
                        'Get poster from TVDB
                        Poster = GetTVPoster(SeriesID)
                        'Indicate something was found
                        TVFound = True
                    End If
                ElseIf AutoMoviePoster Then 'If movie poster capture is enabled
                    If MetaData(2) <> String.Empty Then 'If a file metadata ID was captured continue
                        'If the metadata ID contains "MV" use the title and year from the metadata
                        If MetaData(2).Substring(0, 2) = "MV" Then
                            Title = MetaData(0)
                            TMDbID = GetMovieID(MetaData(0), MetaData(5))
                        End If
                    Else 'Otherwise use the filename for the movie title
                        Title = Outfile
                        TMDbID = GetMovieID(Outfile)
                        If TMDbID(1) <> String.Empty Then
                            Title = TMDbID(1)
                        End If
                    End If

                    'If a TMDB ID was captured get a poster and set it to found
                    If TMDbID(0) <> "" Then
                        Poster = GetMoviePoster(TMDbID(0))
                        MovieFound = True
                    End If
                End If

                If TVFound Then 'Continue if something was found
                    If Poster = "" Then 'If no poster was found create atomicparsley command line without artwork
                        Posters(Video) = ""
                        AtomicArgs(Video) = """" & OutPath & "\" & Outfile & ".m4v"" --TVShowName """ & MetaData(0) & """ --TVEpisode """ & MetaData(1) & """ --TVSeasonNum " & EpisodeData(0).ToString & " --TVEpisodeNum " & EpisodeData(1).ToString & " --stik ""TV Show"" --title """ & MetaData(1) & """ --overWrite"
                    Else 'Otherwise include artwork
                        Posters(Video) = Poster
                        AtomicArgs(Video) = """" & OutPath & "\" & Outfile & ".m4v"" --TVShowName """ & MetaData(0) & """ --TVEpisode """ & MetaData(1) & """ --TVSeasonNum " & EpisodeData(0).ToString & " --TVEpisodeNum " & EpisodeData(1).ToString & " --stik ""TV Show"" --title """ & MetaData(1) & """ --overWrite --artwork """ & Poster & """"
                    End If
                ElseIf MovieFound And Poster <> "" Then 'If a movie poster was found create command line
                    Posters(Video) = Poster
                    AtomicArgs(Video) = """" & OutPath & "\" & Outfile & ".m4v"" --stik ""Movie"" --title """ & Title & """ --overWrite --artwork """ & Poster & """"
                End If

            Next
        End If

        'start looping through videos in list box
        For Video As Integer = 1 To VideoCount
            'get the filename of the input file without extension
            Outfile = Path.GetFileNameWithoutExtension(lstVideos.Items(0).ToString)
            'get the path to the input file
            InPath = Path.GetDirectoryName(lstVideos.Items(0).ToString)
            'create file path for input video's edl file

            If InPath.Substring((InPath.Length - 1), 1) = "\" Then
                edlFile = InPath & Outfile & ".edl"
            Else
                edlFile = InPath & "\" & Outfile & ".edl"
            End If

            'check if an edl file exists for the input video
            'use edl file if it exists and RemoveAds is selected
            If File.Exists(edlFile) And RemoveAds Then
                Dim edlFileRead As StreamReader
                Dim numlines As Integer = 0

                edlFileRead = File.OpenText(edlFile)

                'run through edl file to determine the number of lines
                Do While edlFileRead.Peek <> -1
                    edlFileRead.ReadLine()
                    numlines += 1
                Loop

                edlFileRead.Close()

                Dim edldata(numlines, 1) As Single
                Dim parts As Integer = 0
                Dim edlLine() As String
                Dim mp4box As New Process
                Dim progress As Single = 0
                Dim currprog As Single = 0

                edlFileRead = File.OpenText(edlFile)

                'read lines from edl file and put values into edldata array
                For x As Integer = 0 To (numlines - 1)
                    edlLine = edlFileRead.ReadLine.Split
                    For y As Integer = 0 To 1
                        edldata(x, y) = edlLine(y)
                    Next
                Next

                edlFileRead.Close()

                'if the very first ad break begins at the beginning of the video decrement numlines by 1
                If edldata(0, 0) = 0 Then
                    numlines -= 1
                End If

                'make progress bar, progress label, and cancel button visible
                lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - 0.0%"
                encodeProgress.Value = 0
                encodeProgress.Visible = True
                lblPerComp.Visible = True
                btnCancel.Visible = True

                'begin processing and encoding each section of "show" video sections
                For arrayLine As Integer = 0 To (numlines - 1)
                    'increment the number of video parts by 1
                    parts += 1
                    'determine which arguments to use based on edl data
                    If Not edldata(0, 0) = 0 And arrayLine = 0 Then
                        'if the first edl value is not 0 start encoding from the beginning and stop at the first value
                        Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & "." & (arrayLine + 1).ToString & ".m4v"" --stop-at duration:" & edldata(0, 0).ToString
                    ElseIf edldata(arrayLine, 0) = edldata(arrayLine, 1) Then
                        'if the two edl values are equal this indicates the end of the video
                        'encoding should start at the second value of the previous edl line and go to the end of the video
                        Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & "." & (arrayLine + 1).ToString & ".m4v"" --start-at duration:" & edldata((arrayLine - 1), 1).ToString
                        'set arrayLine to equal numlines so that loop will not go again
                        arrayLine = numlines
                    ElseIf edldata(0, 0) = 0 And edldata((arrayLine + 1), 0) = edldata((arrayLine + 1), 1) Then
                        'if the very first edl value is 0 and the values on the next line are equal
                        'use the current second value as a start and encode to the end
                        Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & "." & (arrayLine + 1).ToString & ".m4v"" --start-at duration:" & edldata(arrayLine, 1).ToString
                    Else
                        'otherwise the section of video is in the middle and needs a duration
                        If edldata(0, 0) = 0 Then
                            'first edl value is 0, use duration from first edl value on next line to the second edl value on current line
                            'start at second edl value on current line
                            Dim duration As Single = edldata(arrayLine + 1, 0) - edldata((arrayLine), 1)
                            Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & "." & (arrayLine + 1).ToString & ".m4v"" --start-at duration:" & edldata(arrayLine, 1).ToString & " --stop-at duration:" & duration.ToString
                        Else
                            'otherwise, use duration from first edl value on current line to the second edl value on previous line
                            'start at second edl value on previous line
                            Dim duration As Single = edldata(arrayLine, 0) - edldata((arrayLine - 1), 1)
                            Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & "." & (arrayLine + 1).ToString & ".m4v"" --start-at duration:" & edldata((arrayLine - 1), 1).ToString & " --stop-at duration:" & duration.ToString
                        End If
                    End If
                    Application.DoEvents()
                    'set process properties and start HandBrakeCLI
                    handbrake.StartInfo.UseShellExecute = False
                    handbrake.StartInfo.CreateNoWindow = True
                    handbrake.StartInfo.RedirectStandardOutput = True
                    handbrake.StartInfo.FileName = HBPath
                    handbrake.StartInfo.Arguments = Args
                    handbrake.Start()
                    'start capturing the stdout from HandBrakeCLI
                    Dim stdout As StreamReader = handbrake.StandardOutput

                    'HandBrakeCLI has two progress percentages when --start-at is used
                    'one for seek and once it finds the start point begins encoding

                    'start processing stdout
                    'if the first edl value is not 0 we only need to process encoding progress
                    If Not edldata(0, 0) = 0 And arrayLine = 0 Then
                        'wait for "Encoding:" to appear at the beginning of the standard output
                        Do
                            output = Split(stdout.ReadLine)
                        Loop Until output(0) = "Encoding:"

                        'capture stdout until encoding is finished
                        Do
                            'split stdout line
                            output = Split(stdout.ReadLine)
                            'make sure the number of values on line is valid before processing
                            If output.Length >= 6 Then
                                If Single.TryParse(output(5), percentage) Then
                                    'capture progress from stdout and calculate overall current progress
                                    currprog = percentage / numlines
                                    'set progress bar value and progress label
                                    encodeProgress.Value = CInt(currprog)
                                    lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & currprog.ToString("###.#") & "%"
                                    'calculate total progress for all videos and set window title
                                    'set value on taskbar progress if running on Windows 7 or higher
                                    AllProgress = (100 * (Video - 1) + currprog) / VideoCount
                                    Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                                    If OsMajor >= 6 And OsMinor >= 1 Then
                                        TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                                    End If
                                End If
                            End If

                            'take user input
                            Application.DoEvents()
                            'if the cancel button was pressed kill HandBrakeCLI, wait for it to exit and delete all parts of the output video
                            'stop processing videos
                            If KillHB Then
                                handbrake.Kill()
                                handbrake.WaitForExit()
                                For prt As Integer = 1 To (arrayLine + 1)
                                    System.IO.File.Delete(OutPath & "\" & Outfile & "." & prt.ToString & ".m4v")
                                Next
                                For Poster As Integer = 0 To (Posters.Length - 1)
                                    If Posters(Poster) <> String.Empty Then
                                        File.Delete(Posters(Poster))
                                    End If
                                Next
                                Exit For
                            End If
                            'Loop Until HandBrakeCLI has finished and exited
                        Loop Until handbrake.HasExited

                        'update the progress based on what it should be, captured stdout usually doesn't get to 100.0
                        progress = 100 / numlines
                        encodeProgress.Value = CInt(progress)
                        lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & progress.ToString("###.#") & "%"
                        AllProgress = (100 * (Video - 1) + progress) / VideoCount
                        Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                        'if on Windows 7 set taskbar progress
                        If OsMajor >= 6 And OsMinor >= 1 Then
                            TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                        End If
                    Else
                        'section is in the middle or end of video

                        'wait for "Encoding:" to appear at the beginning of the standard output
                        Do
                            output = Split(stdout.ReadLine)
                        Loop Until output(0) = "Encoding:"

                        'capture stdout until seeking is finished
                        Do
                            'split stdout line
                            output = Split(stdout.ReadLine)
                            'make sure the number of values on line is valid before processing
                            If output.Length >= 10 Then
                                If Single.TryParse(output(9), percentage) AndAlso percentage > 0 Then
                                    'capture progress from stdout and calculate overall current progress
                                    currprog = progress + (percentage / numlines / 2)
                                    'set progress bar value and progress label
                                    encodeProgress.Value = CInt(currprog)
                                    lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & currprog.ToString("###.#") & "%"
                                    'calculate total progress for all videos and set window title
                                    'set value on taskbar progress if running on Windows 7 or higher
                                    AllProgress = (100 * (Video - 1) + currprog) / VideoCount
                                    Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                                    If OsMajor >= 6 And OsMinor >= 1 Then
                                        TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                                    End If
                                End If
                            End If

                            'take user input
                            Application.DoEvents()
                            'if the cancel button was pressed kill HandBrakeCLI, wait for it to exit and delete all parts of the output video
                            'stop processing videos
                            If KillHB Then
                                handbrake.Kill()
                                handbrake.WaitForExit()
                                For prt As Integer = 1 To (arrayLine + 1)
                                    System.IO.File.Delete(OutPath & "\" & Outfile & "." & prt.ToString & ".m4v")
                                Next
                                Exit Do
                            End If
                            'loop until the captured percentage rounds up to 100 to prevent an infinite loop
                        Loop Until CInt(percentage) > 90
                        'update progress and total progress to make up for current progress not reaching 100%
                        progress += 100 / numlines / 2
                        encodeProgress.Value = CInt(progress)
                        lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & progress.ToString("###.#") & "%"
                        AllProgress = (100 * (Video - 1) + progress) / VideoCount
                        Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                        If OsMajor >= 6 And OsMinor >= 1 Then
                            TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                        End If
                        'exit for loop if cancel button is pressed and clean up handbrake process
                        If KillHB Then
                            stdout.DiscardBufferedData()
                            stdout.Dispose()
                            handbrake.WaitForExit()
                            handbrake.Close()
                            For Poster As Integer = 0 To (Posters.Length - 1)
                                If Posters(Poster) <> String.Empty Then
                                    File.Delete(Posters(Poster))
                                End If
                            Next
                            Exit For
                        End If

                        'wait for encoding to start
                        Do
                            output = Split(stdout.ReadLine)
                        Loop Until output(0) = "Encoding:"
                        'capture stdout until encoding is finished
                        Do
                            'split stdout line
                            output = Split(stdout.ReadLine)
                            'make sure the number of values on line is valid before processing
                            If output.Length >= 6 Then
                                If Single.TryParse(output(5), percentage) AndAlso percentage > 0 Then
                                    'capture progress from stdout and calculate overall current progress
                                    currprog = progress + (percentage / numlines / 2)
                                    'set progress bar value and progress label
                                    encodeProgress.Value = CInt(currprog)
                                    lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & currprog.ToString("###.#") & "%"
                                    'calculate total progress for all videos and set window title
                                    'set value on taskbar progress if running on Windows 7 or higher
                                    AllProgress = (100 * (Video - 1) + currprog) / VideoCount
                                    Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                                    If OsMajor >= 6 And OsMinor >= 1 Then
                                        TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                                    End If
                                End If
                            End If

                            'take user input
                            Application.DoEvents()
                            'if the cancel button was pressed kill HandBrakeCLI, wait for it to exit and delete all parts of the output video
                            'stop processing videos
                            If KillHB Then
                                handbrake.Kill()
                                handbrake.WaitForExit()
                                For prt As Integer = 1 To (arrayLine + 1)
                                    System.IO.File.Delete(OutPath & "\" & Outfile & "." & prt.ToString & ".m4v")
                                Next
                                Exit Do
                            End If
                            'loop until HandBrakeCLI has exited
                        Loop Until handbrake.HasExited
                        'update progress and total progress to make up for current progress not reaching 100%
                        If Not KillHB Then
                            progress += 100 / numlines / 2
                            encodeProgress.Value = CInt(progress)
                            lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & progress.ToString("###.#") & "%"
                            AllProgress = (100 * (Video - 1) + progress) / VideoCount
                            Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                            If OsMajor >= 6 And OsMinor >= 1 Then
                                TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                            End If
                        End If
                    End If

                    'clean up handbrake process
                    stdout.DiscardBufferedData()
                    stdout.Dispose()
                    handbrake.WaitForExit()
                    handbrake.Close()

                    'if cancel was pressed exit for loop
                    If KillHB Then
                        For Poster As Integer = 0 To (Posters.Length - 1)
                            If Posters(Poster) <> String.Empty Then
                                File.Delete(Posters(Poster))
                            End If
                        Next
                        Exit For
                    End If
                Next

                'make progress bar, label, and cancel button invisible
                lblPerComp.Visible = False
                encodeProgress.Visible = False
                btnCancel.Visible = False

                'use mp4box to combine video parts if cancel button not pressed
                If Not KillHB Then
                    Args = ""
                    'create arguments for mp4box to combine video files
                    For part As Integer = 1 To parts
                        If part = 1 Then
                            ' First one must be done with 'add' otherwise a busted file happens
                            Args += "-add """ & OutPath & "\" & Outfile & "." & part & ".m4v"" "
                        Else
                            Args += "-cat """ & OutPath & "\" & Outfile & "." & part & ".m4v"" "
                        End If
                    Next
                    Args += """" & OutPath & "\" & Outfile & ".m4v"""
                    Me.Text = "Batch Video Converter - Running MP4Box"
                    'set mp4box process properties
                    mp4box.StartInfo.UseShellExecute = False
                    mp4box.StartInfo.CreateNoWindow = True
                    mp4box.StartInfo.RedirectStandardOutput = False
                    mp4box.StartInfo.FileName = mp4boxPath
                    mp4box.StartInfo.Arguments = Args
                    'start mp4box and wait for it to close
                    mp4box.Start()
                    mp4box.WaitForExit()
                    mp4box.Close()
                    Me.Text = "Batch Video Converter"
                    'delete parts of video
                    For part As Integer = 1 To parts
                        System.IO.File.Delete(OutPath & "\" & Outfile & "." & part & ".m4v")
                    Next
                End If
            Else
                'no EDL file exists or if commercial removal disabled 
                Dim progress As Single

                'set HandBrakeCLI arguments
                Args = CropVideo & "-Z """ & EncodeTo & """ -i """ & lstVideos.Items(0).ToString & """ -o """ & OutPath & "\" & Outfile & ".m4v"""

                'make progress bar, label, and cancel button visible
                lblPerComp.Visible = True
                encodeProgress.Visible = True
                btnCancel.Visible = True

                'set handbrake process properties
                handbrake.StartInfo.UseShellExecute = False
                handbrake.StartInfo.CreateNoWindow = True
                handbrake.StartInfo.RedirectStandardOutput = True
                handbrake.StartInfo.FileName = HBPath
                handbrake.StartInfo.Arguments = Args

                'start HandbrakeCLI and start capturing stdout
                handbrake.Start()
                Dim stdout As StreamReader = handbrake.StandardOutput

                'start processing stdout
                'wait for encoding to appear on stdout line
                Do
                    output = Split(stdout.ReadLine)
                Loop Until output(0) = "Encoding:"

                'capture stdout until encoding is finished
                Do
                    'split stdout line
                    output = Split(stdout.ReadLine)
                    'make sure the number of values on line is valid before processing
                    If output.Length >= 6 Then
                        If Single.TryParse(output(5), percentage) Then
                            'capture progress from stdout and calculate progress                            
                            progress = CSng(percentage)
                            'set progress bar value and progress label
                            encodeProgress.Value = CInt(progress)
                            lblPerComp.Text = "Video: " & Video.ToString & "/" & VideoCount.ToString & " - " & progress.ToString("###.#") & "%"
                            'calculate total progress for all videos and set window title
                            'set value on taskbar progress if running on Windows 7 or higher
                            AllProgress = (100 * (Video - 1) + progress) / VideoCount
                            Me.Text = "Batch Video Converter - " & AllProgress.ToString("###.#") & "%"
                            If OsMajor >= 6 And OsMinor >= 1 Then
                                TaskbarManager.Instance.SetProgressValue(CInt(AllProgress), 100)
                            End If
                        End If
                    End If

                    'take user input
                    Application.DoEvents()
                    'if the cancel button was pressed kill HandBrakeCLI, wait for it to exit
                    'delete all parts of the output video
                    'stop processing videos
                    If KillHB Then
                        handbrake.Kill()
                        handbrake.WaitForExit()
                        File.Delete(OutPath & "\" & Outfile & ".m4v")
                        Exit Do
                    End If
                Loop Until handbrake.HasExited

                'clean up handbrake process
                stdout.DiscardBufferedData()
                stdout.Dispose()
                handbrake.Close()

                'make progress bar, label, and cancel button invisible
                lblPerComp.Visible = False
                encodeProgress.Visible = False
                btnCancel.Visible = False
            End If

            'if cancel button was pressed set kill variable back to false and exit for loop
            If KillHB Then
                KillHB = False
                If AutoTVMeta Or AutoMoviePoster Then
                    Dim AlreadyDeleted(Posters.Length - 1) As String
                    Dim Deleted As Boolean = False
                    Dim DeletedPosters As Integer = 0
                    For Poster As Integer = Video - 1 To (Posters.Length - 1)
                        Deleted = False
                        For x As Integer = 0 To AlreadyDeleted.Length - 1
                            If AlreadyDeleted(x) = Posters(Poster) Then
                                Deleted = True
                                Exit For
                            End If
                        Next
                        If Posters(Poster) <> String.Empty And Deleted = False Then
                            File.Delete(Posters(Poster))
                            AlreadyDeleted(DeletedPosters) = Posters(Poster)
                            DeletedPosters += 1
                        End If
                    Next
                End If
                Exit For
            End If

            If AutoTVMeta Or AutoMoviePoster Then

                Me.Text = "Running Atomic Parsley"

                If AtomicArgs(Video - 1) <> String.Empty Then ' If arguments were generated run atomicparsley
                    Using atomic As New Process
                        atomic.StartInfo.UseShellExecute = False
                        atomic.StartInfo.CreateNoWindow = True
                        atomic.StartInfo.RedirectStandardOutput = False
                        atomic.StartInfo.FileName = APPath
                        atomic.StartInfo.Arguments = AtomicArgs(Video - 1)
                        atomic.Start()
                        atomic.WaitForExit()
                        atomic.Close()
                    End Using
                End If

                Me.Text = "Batch Video Converter"

                'Delete poster if it exists
                If Posters(Video - 1) <> String.Empty Then
                    If Video = Posters.Length Then
                        File.Delete(Posters(Video - 1))
                    Else
                        DeletePoster = True
                        For x As Integer = Video To Posters.Length - 1
                            If Posters(x) = Posters(Video - 1) Then
                                DeletePoster = False
                                Exit For
                            End If
                        Next
                        If DeletePoster Then
                            File.Delete(Posters(Video - 1))
                        End If
                    End If
                End If
            End If

            'remove first item in list box
            lstVideos.Items.RemoveAt(0)
        Next
        'if on Windows 7 or higher disable taskbar progress
        If OsMajor >= 6 And OsMinor >= 1 Then
            TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress)
        End If
        'set window name back to normal and enable all buttons and radio controls
        Me.Text = "Batch Video Converter"
        btnAdd.Enabled = True
        btnRemove.Enabled = True
        btnClear.Enabled = True
        btnSettings.Enabled = True
        btnEncode.Enabled = True
        grpEncDest.Enabled = True
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        'set open file dialog properties
        openFD.Title = "Open a Video File"
        openFD.Filter = "Video Files (*.AVI;*.M2TS;*.M4V;*.MP4;*.MPG;*.MKV;*.TS)|*.AVI;*.M2TS;*.M4V;*.MP4;*.MPG;*.MKV;*.TS|All Files (*.*)|*.*"
        'if set use lastsource registry value to set the initial directory
        If Not Application.UserAppDataRegistry.GetValue("LastSource") Is Nothing Then
            openFD.InitialDirectory = Application.UserAppDataRegistry.GetValue("LastSource").ToString
        End If
        openFD.FilterIndex = 1
        'show open file dialog and add files to list if ok is pressed
        If openFD.ShowDialog = DialogResult.OK Then
            For Each strFile As String In openFD.FileNames
                lstVideos.Items.Add(strFile)
            Next
            'add the last directory to the lastsource registry entry
            Application.UserAppDataRegistry.SetValue("LastSource", Path.GetDirectoryName(openFD.FileName))
        End If
    End Sub

    Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        'remove selected item from list box
        If lstVideos.SelectedIndex > -1 Then
            lstVideos.Items.RemoveAt(lstVideos.SelectedIndex)
        Else
            MessageBox.Show("Please select a file to remove!")
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        'clear the list box
        lstVideos.Items.Clear()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'set killhb to true if the cancel button is pressed
        KillHB = True
    End Sub

    Private Sub lstVideos_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lstVideos.DragDrop
        Dim files As String()
        'add files to the list box that are dragged on top of it
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            files = CType(e.Data.GetData(DataFormats.FileDrop), String())
            For Each file As String In files
                lstVideos.Items.Add(file)
            Next
        End If
    End Sub

    Private Sub lstVideos_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lstVideos.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub frmBatchVideo_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim osInfo As System.OperatingSystem = System.Environment.OSVersion

        'try to get settings from registry
        If Not Application.UserAppDataRegistry.GetValue("HBPath") Is Nothing Then
            HBPath = Application.UserAppDataRegistry.GetValue("HBPath").ToString
        End If
        If Not Application.UserAppDataRegistry.GetValue("mp4boxPath") Is Nothing Then
            mp4boxPath = Application.UserAppDataRegistry.GetValue("mp4boxPath").ToString
        End If
        If Not Application.UserAppDataRegistry.GetValue("APPath") Is Nothing Then
            APPath = Application.UserAppDataRegistry.GetValue("APPath").ToString
        End If
        If Not Application.UserAppDataRegistry.GetValue("OutPath") Is Nothing Then
            OutPath = Application.UserAppDataRegistry.GetValue("OutPath").ToString
        End If
        If Not Application.UserAppDataRegistry.GetValue("RemoveAds") Is Nothing Then
            RemoveAds = CBool(Application.UserAppDataRegistry.GetValue("RemoveAds"))
        End If
        If Not Application.UserAppDataRegistry.GetValue("AutoCrop") Is Nothing Then
            AutoCrop = CBool(Application.UserAppDataRegistry.GetValue("AutoCrop"))
        End If
        If Not Application.UserAppDataRegistry.GetValue("AutoMeta") Is Nothing Then
            AutoTVMeta = CBool(Application.UserAppDataRegistry.GetValue("AutoMeta"))
        End If
        If Not Application.UserAppDataRegistry.GetValue("AutoMoviePoster") Is Nothing Then
            AutoMoviePoster = CBool(Application.UserAppDataRegistry.GetValue("AutoMoviePoster", AutoMoviePoster))
        End If

        'get the major and minor version numbers of the OS
        OsMajor = osInfo.Version.Major
        OsMinor = osInfo.Version.Minor

        'set temp folder
        TempDir = Path.GetTempPath

        'set the window icon
        Me.Icon = My.Resources.Resource1.film_reel
    End Sub

    Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
        Dim frmSettings As New Settings

        'show the settings dialog box
        frmSettings.ShowDialog()
    End Sub

    Private Sub btnUp_Click(sender As System.Object, e As System.EventArgs) Handles btnUp.Click
        'make sure an item is selected and not the first
        If lstVideos.SelectedIndex > 0 Then
            'get selected item and its index
            Dim objSelectedItem As Object = lstVideos.SelectedItem
            Dim intIndex As Integer = lstVideos.SelectedIndex

            'remove the item that you want to move
            lstVideos.Items.RemoveAt(intIndex)

            'decrement index
            intIndex -= 1

            'insert item at new index
            lstVideos.Items.Insert(intIndex, objSelectedItem)

            'select item
            lstVideos.SelectedIndex = intIndex
        End If
    End Sub

    Private Sub btnDown_Click(sender As System.Object, e As System.EventArgs) Handles btnDown.Click
        'make sure an item is selected and not the last
        If lstVideos.SelectedIndex > -1 And lstVideos.SelectedIndex < (lstVideos.Items.Count - 1) Then
            'get selected item and its index
            Dim objSelectedItem As Object = lstVideos.SelectedItem
            Dim intIndex As Integer = lstVideos.SelectedIndex

            'remove the item that you want to move
            lstVideos.Items.RemoveAt(intIndex)

            'increment index
            intIndex += 1

            'insert item at new index
            lstVideos.Items.Insert(intIndex, objSelectedItem)

            'select item
            lstVideos.SelectedIndex = intIndex
        End If
    End Sub
End Class
